﻿using Microsoft.SharePoint.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace Uportal.Shp.Core.Extension
{
    public static class StringExtention
    {
        public static string EncryptString(this string toEncrypt)
        {
            try
            {
                byte[] keyArray;
                byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
                //System.Configuration.AppSettingsReader settingsReader = new     AppSettingsReader();        
                string Key = "Abirvalg";

                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(Key));
                hashmd5.Clear();

                TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
                tDes.Key = keyArray;
                tDes.Mode = CipherMode.ECB;
                tDes.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = tDes.CreateEncryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0,
                    toEncryptArray.Length);
                tDes.Clear();
                return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
            catch { return "sHlBUF6wwuA="; }
        }

        public static string DecryptString(this string cypherString)
        {
            try
            {
                byte[] keyArray;
                byte[] toDecryptArray = Convert.FromBase64String(cypherString);
                //byte[] toEncryptArray = Convert.FromBase64String(cypherString);      
                //System.Configuration.AppSettingsReader settingReader = new     AppSettingsReader();   
                string key = "Abirvalg";

                MD5CryptoServiceProvider hashmd = new MD5CryptoServiceProvider();
                keyArray = hashmd.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd.Clear();

                TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider();
                tDes.Key = keyArray; tDes.Mode = CipherMode.ECB;
                tDes.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = tDes.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0,
                    toDecryptArray.Length);
                tDes.Clear();
                return UTF8Encoding.UTF8.GetString(resultArray, 0, resultArray.Length);

            }
            catch { return "asd"; }
        }

        public static bool GuidTryParse(this string self, out Guid result)
        {
            if (self == null)
            {
                result = Guid.Empty;
                return false;
            }
            var format = new Regex(
                "^[A-Fa-f0-9]{32}$|" +
                "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
                "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$");
            var match = format.Match(self);
            if (match.Success)
            {
                result = new Guid(self);
                return true;
            }
            else
            {
                result = Guid.Empty;
                return false;
            }
        }

        public static StringBuilder AppendFormatLine(this StringBuilder self, string format, params object[] args)
        {
            if (self == null) throw new ArgumentNullException("self");

            self.AppendLine(string.Format(format, args));

            return self;
        }

        public static string ConvertToUnsecureString(this SecureString securePassword)
        {
            if (securePassword == null)
                throw new ArgumentNullException("securePassword");

            IntPtr unmanagedString = IntPtr.Zero;
            try
            {
                unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword);
                return Marshal.PtrToStringUni(unmanagedString);
            }
            finally
            {
                Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
            }
        }

        public static string FormatXml(this string self)
        {
            // Encode the XML string in a UTF-8 byte array
            byte[] encodedString = Encoding.UTF8.GetBytes(self);

            // Put the byte array into a stream and rewind it to the beginning
            var ms = new MemoryStream(encodedString);

            ms.Flush();
            ms.Position = 0;

            // Build the XmlDocument from the MemorySteam of UTF-8 encoded bytes
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(ms);

            var ms2 = new MemoryStream();
            var xmlWriter = new XmlTextWriter(ms2, Encoding.UTF8);
            xmlWriter.Formatting = Formatting.Indented;
            xmlDoc.WriteContentTo(xmlWriter);
            xmlWriter.Flush();
            ms2.Flush();

            ms2.Position = 0;

            var sr = new StreamReader(ms2);

            return sr.ReadToEnd();
        }

        public static string FormatMultilineText(this string multilinetext)
        {
            multilinetext = SPHttpUtility.ConvertSimpleHtmlToText(multilinetext, -1);
            return multilinetext;
        }
    }
}
